#include "stdafx.h"
#include <MyControls/SegmentSet.h>

namespace My {

// SegmentSet

int SegmentSet::GetActiveSegment()
{
	return 
		GetDoc().GetSelection().Is<SegmentSelection>() ?
			GetDoc().GetSelection().As<SegmentSelection>().GetActive() :
				-1;
}

void SegmentSet::SetActiveSegment(int index)
{
	GetDoc().SetSelection(new SegmentSelection(* this, index));
}

// SegmentSelection

SegmentSelection::SegmentSelection(SegmentSet & s, int active)
	: m_Segments(s), m_Active(-1)
{
	SetActive(active);
}

void SegmentSelection::SetActive(int active)
{
	if (active < -1)
		active = -1;
	if (active > int(m_Segments.GetSegmentCount()) - 1)
		active = int(m_Segments.GetSegmentCount()) - 1;
	if (active != m_Active) {
		int old = m_Active;
		m_Active = active;
		if (old != -1)
			m_Segments.GetSegment(old).DispatchEvent(Segment::StateChange(m_Segments.GetSegment(old)));
		if (m_Active != -1)
			m_Segments.GetSegment(m_Active).DispatchEvent(Segment::StateChange(m_Segments.GetSegment(m_Active)));
		Changed();
	}
}

bool SegmentSelection::IsEmpty() const
{
	return m_Active == -1;
}

void SegmentSelection::Clear()
{
	SetActive(-1);
}

bool SegmentSelection::Erasable() const
{
	return !IsEmpty();
}

void SegmentSelection::Erase()
{
	m_Segments.EraseSelection();
}

bool SegmentSelection::Equals(const Selection & s) const
{
	return s.Is<SegmentSelection>() &&
		s.As<SegmentSelection>().GetActive() == GetActive();
}

} // My